package cn.com.hhrcw.enterprise.web;

import cn.com.hhrcw.enterprise.params.OpDeliveryHistoryParams;
import cn.com.hhrcw.enterprise.vo.EnInfoVO;
import cn.com.hhrcw.enterprise.vo.OpDeliveryHistoryVO;
import cn.com.hhrcw.enterprise.vo.OpJobVO;
import cn.com.hhrcw.enterprise.vo.PiInfoVO;
import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.mapstruct.*;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.utils.AgeUtil;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * 职位-投递记录
 *
 * @author jiangdong
 * @since 2020-10-31
 */
@RestController
@Slf4j
@RequestMapping("/en/opDeliveryHistory")
@Api(tags = "职位-投递记录")
@Validated
public class EnOpDeliveryHistoryController extends JeecgController<OpDeliveryHistory, IOpDeliveryHistoryService> {

    @Autowired
    private IOpDeliveryHistoryService opDeliveryHistoryService;

    @Autowired
    private EnOpDeliveryHistoryConvert opDeliveryHistoryConvert;
    @Autowired
    private IOpJobService jobService;
    @Autowired
    private IEnInfoService enInfoService;
    @Autowired
    private EnEnInfoConvert enInfoConvert;
    @Autowired
    private EnOpJobConvert opJobConvert;

    @Autowired
    private IPiInfoService piInfoService;
    @Autowired
    EnPiInfoConvert piInfoConvert;
    @Autowired
    ICvResumeService resumeService;
    @Autowired
    EnCvResumeConvert resumeConvert;

    /**
     * 投递记录列表
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog(logType = 2, ty = "visit", value = "投递记录列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    public Result<Page<OpDeliveryHistoryVO>> list(OpDeliveryHistoryParams params, HttpServletRequest request) {
        QueryWrapper<OpDeliveryHistory> queryWrapper = QueryGenerator.initQueryWrapper(opDeliveryHistoryConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        queryWrapper.eq("user_id", sysUser.getId());
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(0);
        list.add(3);
        queryWrapper.in("state", list);
        IPage<OpDeliveryHistory> page = opDeliveryHistoryService.page(params.page(), queryWrapper);
        //分页结果转换器

        Function<OpDeliveryHistory, OpDeliveryHistoryVO> fun = opDeliveryHistory -> {
            OpDeliveryHistoryVO e = opDeliveryHistoryConvert.toVO(opDeliveryHistory);
            String jobId = e.getJobId();
            OpJob job = jobService.getById(jobId);
            String companyId = e.getCompanyId();
            EnInfo enInfo = enInfoService.getById(companyId);
            EnInfoVO enInfoVO = enInfoConvert.toVO(enInfo);
            OpJobVO jobVO = opJobConvert.toVO(job);
            e.setOpJob(jobVO);
            e.setEnInfo(enInfoVO);
            return e;
        };
        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @AutoLog(logType = 2, ty = "visit", value = "投递记录信息查询")
    public Result<OpDeliveryHistoryVO> queryById(String id) {
        OpDeliveryHistory opDeliveryHistory = opDeliveryHistoryService
                .lambdaQuery()
                .eq(OpDeliveryHistory::getId, id)
                .eq(OpDeliveryHistory::getDelFlag, false)
                .one();
        if (opDeliveryHistory == null) {
            throw new JeecgBootException("数据不存在");
        }
        OpDeliveryHistoryVO vo = opDeliveryHistoryConvert.toVO(opDeliveryHistory);
        String jobId = vo.getJobId();
        OpJob job = jobService.getById(jobId);
        String companyId = vo.getCompanyId();
        EnInfo enInfo = enInfoService.getById(companyId);
        EnInfoVO enInfoVO = enInfoConvert.toVO(enInfo);
        OpJobVO jobVO = opJobConvert.toVO(job);
        String userId = vo.getUserId();
        CvResume resume = resumeService.getById(vo.getResumeId());
        vo.setResumeVO(resumeConvert.toVO(resume));
        PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, userId).one();
        PiInfoVO piInfoVO = piInfoConvert.toVO(piInfo);
        if (piInfoVO.getJobTime() != null) {
            piInfoVO.setWorkYears(AgeUtil.getAge(piInfoVO.getJobTime()));
        }
        vo.setUserInfo(piInfoVO);
        vo.setOpJob(jobVO);
        vo.setEnInfo(enInfoVO);
        return Result.ok(vo);
    }


    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog(logType = 2, ty = "update", value = "投递记录编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("opDeliveryHistory:edit")
    public Result<?> edit(@RequestBody @Valid OpDeliveryHistoryParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OpDeliveryHistory opDeliveryHistory = opDeliveryHistoryConvert.toEntity(params);
        opDeliveryHistory.setUpdateBy(sysUser.getId());
        opDeliveryHistory.setUpdateTime(DateUtil.date());

        boolean updated = opDeliveryHistoryService.updateById(opDeliveryHistory);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog(logType = 2, ty = "delete", value = "投递记录删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("opDeliveryHistory:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<OpDeliveryHistory> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(OpDeliveryHistory::getId, id)
                .set(OpDeliveryHistory::getDelFlag, true)
                .set(OpDeliveryHistory::getUpdateBy, sysUser.getUsername())
                .set(OpDeliveryHistory::getUpdateTime, DateUtil.date());

        boolean deleted = opDeliveryHistoryService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, OpDeliveryHistoryParams params) {
        OpDeliveryHistory opDeliveryHistory = opDeliveryHistoryConvert.toEntity(params);
        opDeliveryHistory.setDelFlag(false);
        QueryWrapper<OpDeliveryHistory> queryWrapper = QueryGenerator.initQueryWrapper(opDeliveryHistory, request.getParameterMap());
        List<OpDeliveryHistory> data = opDeliveryHistoryService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("职位-投递记录", "职位-投递记录");
        String url = super.exportXls(exportParams, OpDeliveryHistoryVO.class, opDeliveryHistoryConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OpDeliveryHistory.class);
    }

}
